package com.alkaid.anime.service.impl;

import com.alibaba.fastjson.JSON;
import com.alkaid.anime.mapper.IndicatorMapper;
import com.alkaid.anime.service.IndicatorService;
import com.alkaid.anime.utils.RedisUtils;
import com.alkaid.commons.core.CacheKeyDefinition;
import com.alkaid.commons.entity.Indicator;
import com.alkaid.commons.ex.IllegalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Kylin
 */
@Service
public class IndicatorServiceImpl implements IndicatorService {

    private IndicatorMapper indicatorMapper;

    private RedisUtils redisUtils;

    @Autowired
    public void setIndicatorMapper(IndicatorMapper indicatorMapper) {
        this.indicatorMapper = indicatorMapper;
    }

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public List<Indicator> getIndicators(Integer page) throws IllegalException {
        if (page == null) {
            throw new IllegalException("轮播图非法访问");
        }
        String key = CacheKeyDefinition.getIndicatorKey(page);
        Object value = redisUtils.getFromRedis(key);
        List<Indicator> indicators;
        if (value != null) {
            indicators = JSON.parseArray(value.toString(), Indicator.class);
        } else {
            String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            indicators = indicatorMapper.findIndicators(page, now);
            if (indicators != null) {
                redisUtils.save2Redis(key, indicators, CacheKeyDefinition.CACHE_TIME_DAY);
            }
        }
        if (indicators == null || indicators.size() == 0) {
            throw new IllegalException("轮播图非法访问");
        }
        return indicators;
    }
}
